package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

public class Ingreso extends javax.swing.JInternalFrame {
    private JDatePickerImpl selector_fecha;
    private JCheckBox jchkFechaVencimiento;
    private DefaultListModel<ModeloItemValor> modelo = new DefaultListModel<ModeloItemValor>();
    private ArrayList<detalleentrada> total_ib;
    private ArrayList<detalleentrada2> detalles;
    private String id_bitacora;
    private JFileChooser selector;
    public Ingreso() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("ingreso.xls"));
        jlstProductos.setModel(modelo);
        total_ib = new ArrayList<detalleentrada>();
        detalles = new ArrayList<detalleentrada2>();
        jchkFechaVencimiento = new JCheckBox("",false);
        jchkFechaVencimiento.setToolTipText("Incluir Fecha de Vencimiento");
        selector_fecha = Util.ColocarSelectorFecha(jpFechaVencimiento, null,new Component[]{jchkFechaVencimiento});
        CargarBodegas();
        CargarMarcas();
        CargarProveedores();
        Util.OcultarColumna(jtblDistribucion, 0);
        Util.OcultarColumna(jtblDistribucion, 2);
        Util.OcultarColumna(jtblDistribucion, 5);
        Util.OcultarColumna(jtblDistribucion, 7);
        
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }
    public void Limpiar() {
        jtfProducto.setText(null);
        jcbBodega.setSelectedIndex(-1);
        jcbMarca.setSelectedIndex(-1);
        jcbProveedor.setSelectedIndex(-1);
        jtaObservaciones.setText(null);
        while(jtblDistribucion.getRowCount()>0)
            ((DefaultTableModel)jtblDistribucion.getModel()).removeRow(0);
        modelo.removeAllElements();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfProducto = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblDistribucion = new javax.swing.JTable();
        jbtnDistribuit = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jcbBodega = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jpFechaVencimiento = new javax.swing.JPanel();
        jbtnQuitar = new javax.swing.JButton();
        jbtnExportar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlstProductos = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jtaObservaciones = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jcbMarca = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jcbProveedor = new javax.swing.JComboBox();

        setClosable(true);
        setMaximizable(true);
        setTitle("Ingreso y Distribución de Productos");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/ingresos.png"))); // NOI18N
        setVisible(false);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Producto");

        jtfProducto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfProductoKeyTyped(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Distribucion"));

        jtblDistribucion.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID_Inventario", "Producto", "ID_Bodega", "Bodega", "Fecha Vencimiento", "ID_Marca", "Marca", "ID_Proveedor", "Proveedor", "Cantidad", "Precio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Long.class, java.lang.String.class, java.lang.Long.class, java.lang.String.class, java.lang.Long.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtblDistribucion);

        jbtnDistribuit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnDistribuit.setToolTipText("Agregar Marca y Proveedor");
        jbtnDistribuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnDistribuitActionPerformed(evt);
            }
        });

        jLabel2.setText("Bodega:");

        jLabel3.setText("Fecha de Vencimiento:");

        javax.swing.GroupLayout jpFechaVencimientoLayout = new javax.swing.GroupLayout(jpFechaVencimiento);
        jpFechaVencimiento.setLayout(jpFechaVencimientoLayout);
        jpFechaVencimientoLayout.setHorizontalGroup(
            jpFechaVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 168, Short.MAX_VALUE)
        );
        jpFechaVencimientoLayout.setVerticalGroup(
            jpFechaVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        jbtnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_eliminar.png"))); // NOI18N
        jbtnQuitar.setToolTipText("Agregar Marca y Proveedor");
        jbtnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnQuitarActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbBodega, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(36, 36, 36)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpFechaVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtnDistribuit, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jpFechaVencimiento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jcbBodega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(jbtnDistribuit, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jlstProductos);

        jLabel4.setText("Observaciones:");

        jtaObservaciones.setColumns(20);
        jtaObservaciones.setRows(5);
        jScrollPane5.setViewportView(jtaObservaciones);

        jLabel5.setText("Marca:");

        jLabel6.setText("Proveedor:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jcbMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jcbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(54, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jcbMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jcbProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtfProducto))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(367, 367, 367))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jtfProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void CargarBodegas() {
        jcbBodega.removeAllItems();
        Util.CargarJComboBox(jcbBodega, "SELECT id_bodega,nombre FROM bodega",new String[]{"id","nombre"});
    }
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if (jtblDistribucion.getRowCount() > 0) {
            if (verificarCantidades()){
                if(verificarPrecios()){
                    Guardar();
                    Limpiar();
                }
                else
                    JOptionPane.showMessageDialog(null, "Los precios deben ser mayor que cero", "Ingreso y Distribución de Productos", JOptionPane.ERROR_MESSAGE);
            }
            else
                JOptionPane.showMessageDialog(null, "Cantidad debe ser mayor que cero", "Ingreso y Distribución de Productos", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "Debe agregar al menos un producto", "Ingreso y Distribución de Productos", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void Guardar() {
        SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
        String fecha = formato.format(new Date());
        String[] detalle = Sumatoria_producto();
        String[] detalle2 = detalleProducto();

        if (Conexion.EjecutarProcedimientoAlmacenado("CALL IngresoDistribucion('"+fecha+"','"+Util.ComponerTexto(jtaObservaciones.getText())+"','"
                +detalle[0]+"','"+detalle[1]+"',"+"'"+detalle[2]+"','"+detalle[3]+"','"+detalle2[4]+"','"+detalle2[0]+"','"+detalle2[1]+"','"
                +detalle2[3]+"','"+detalle2[2]+"')")) {
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Guardar Ingreso: "+Util.ComponerTexto(jtaObservaciones.getText()));
                    JOptionPane.showMessageDialog(null, "Distribución Realizada!", "Ingreso y Distribución", JOptionPane.INFORMATION_MESSAGE);
        } 
        else
            JOptionPane.showMessageDialog(null, "No se pudo Realizar la Distribución!", "Error", JOptionPane.ERROR_MESSAGE);
    }
    private boolean verificarCantidades() {
        for (int i = 0; i < jtblDistribucion.getRowCount(); i++)
            if (new Integer(jtblDistribucion.getValueAt(i, 9).toString()) < 1)
                return false;
        return true;
    }
    private boolean verificarPrecios(){
        for(int i=0;i<jtblDistribucion.getRowCount();i++)
            if(new Integer(jtblDistribucion.getValueAt(i,10).toString())<1)
                return false;
        return true;
    }
    private String[] Sumatoria_producto() {
        total_ib.removeAll(total_ib);
        
        String[] detalle = {"", "", "", ""};
        int inventario, proveedor, marca,cantidad;
        boolean existe;
        for (int i = 0; i < jtblDistribucion.getRowCount(); i++) {
            inventario = new Integer(jtblDistribucion.getValueAt(i, 0).toString());
            proveedor = new Integer(jtblDistribucion.getValueAt(i, 7).toString());
            marca = new Integer(jtblDistribucion.getValueAt(i, 5).toString());
            cantidad=new Integer(jtblDistribucion.getValueAt(i, 9).toString());
            existe=false;
            for (int j = 0; j < total_ib.size(); j++) {
                if (total_ib.get(j).Inventario == inventario && total_ib.get(j).marca == marca && total_ib.get(j).proveedor == proveedor) {
                    total_ib.get(j).cantidad += new Integer(jtblDistribucion.getValueAt(i, 9).toString());
                    existe = true;
                    break;
                }
            }
            if(!existe)
                total_ib.add(new detalleentrada(inventario, cantidad, marca, proveedor));
        }
        for (int i = 0; i < total_ib.size(); i++) {
            if (i == total_ib.size() - 1) {
                detalle[0] += total_ib.get(i).Inventario;
                detalle[1] += total_ib.get(i).cantidad;
                detalle[2] += total_ib.get(i).marca;
                detalle[3] += total_ib.get(i).proveedor;
            } else {
                detalle[0] += total_ib.get(i).Inventario + ",";
                detalle[1] += total_ib.get(i).cantidad + ",";
                detalle[2] += total_ib.get(i).marca + ",";
                detalle[3] += total_ib.get(i).proveedor + ",";
            }
        }
        return detalle;
    }
    private String[] detalleProducto() {
        detalles.removeAll(detalles);
        
        String[] detalle_producto = {"", "", "", "", ""};
        int inventario, bodega, precio,cantidad;
        String fecha;

        for (int i = 0; i < jtblDistribucion.getRowCount(); i++) {
            inventario = new Integer(jtblDistribucion.getValueAt(i, 0).toString());
            fecha = (jtblDistribucion.getValueAt(i, 4).toString().equals("-") ? "9999/12/31" : GetFechaFormateada(jtblDistribucion.getValueAt(i, 4).toString()));
            bodega = new Integer(jtblDistribucion.getValueAt(i, 2).toString());
            precio = new Integer(jtblDistribucion.getValueAt(i, 10).toString());
            cantidad=new Integer(jtblDistribucion.getValueAt(i, 9).toString());
            detalles.add(new detalleentrada2(inventario, cantidad, bodega, fecha, precio));
        }
        for (int i = 0; i < detalles.size(); i++) {
            if (i == detalles.size() - 1) {
                detalle_producto[0] += detalles.get(i).inventario;
                detalle_producto[1] += detalles.get(i).cantidad;
                detalle_producto[2] += detalles.get(i).bodega;
                detalle_producto[3] += detalles.get(i).fecha;
                detalle_producto[4] += detalles.get(i).precio;
            } else {
                detalle_producto[0] += detalles.get(i).inventario + ",";
                detalle_producto[1] += detalles.get(i).cantidad + ",";
                detalle_producto[2] += detalles.get(i).bodega + ",";
                detalle_producto[3] += detalles.get(i).fecha + ",";
                detalle_producto[4] += detalles.get(i).precio + ",";
            }
        }
        return detalle_producto;
    }
    private String GetFechaFormateada(String f){
        return f.substring(f.lastIndexOf("/")+1)+"/"+f.substring(f.indexOf("/")+1,f.lastIndexOf("/"))+"/"+f.substring(0,f.indexOf("/"));
    }
    private void CargarProducto(char tecla){
        modelo.removeAllElements();
        JTable tabla = Conexion.ObtenerTabla("SELECT i.id_inventario,CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) AS descripcion FROM inventario i "
                            +"INNER JOIN producto p ON i.id_producto=p.id_producto WHERE p.nombre LIKE '"
                            +Util.ComponerTexto(jtfProducto.getText()+tecla)+"%'",new String[]{"id","descripcion"});
        for (int i = 0; i < tabla.getRowCount(); i++)
            modelo.addElement(new ModeloItemValor(tabla.getValueAt(i, 1), tabla.getValueAt(i, 0)));
    }
    private void CargarProveedores() {
        jcbProveedor.removeAllItems();
        Util.CargarJComboBox(jcbProveedor, "SELECT id_proveedor,nombre FROM proveedor",new String[]{"id","nombre"});
    }
    private void CargarMarcas() {
        jcbMarca.removeAllItems();
        Util.CargarJComboBox(jcbMarca, "SELECT id_marca,descripcion FROM marca",new String[]{"id","nombre"});
    }
    private class detalleentrada {
        public int Inventario, cantidad, marca, proveedor;
        public detalleentrada(int inventario, int cantidad, int marca, int proveedor) {
            this.Inventario = inventario;
            this.cantidad = cantidad;
            this.marca = marca;
            this.proveedor = proveedor;
        }
    }
    private class detalleentrada2 {
        public int inventario, cantidad, bodega;
        public float precio;
        public String fecha;
        public detalleentrada2(int inventario, int cantidad, int bodega, String fecha, float precio) {
            this.inventario = inventario;
            this.cantidad = cantidad;
            this.fecha = fecha;
            this.bodega = bodega;
            this.precio = precio;
        }
    }
    private void jbtnDistribuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDistribuitActionPerformed
        ModeloItemValor miv_pro = (ModeloItemValor) jlstProductos.getSelectedValue();
        ModeloItemValor miv_bod = (ModeloItemValor) jcbBodega.getSelectedItem();
        ModeloItemValor miv_mar = (ModeloItemValor) jcbMarca.getSelectedItem();
        ModeloItemValor miv_prov = (ModeloItemValor) jcbProveedor.getSelectedItem();
        String fecha_vencimiento = "-";
        if (jchkFechaVencimiento.isSelected()) {
            Date fecha = ((Date) selector_fecha.getModel().getValue());
            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
            fecha_vencimiento = formato.format(fecha);
        }
        ((DefaultTableModel) jtblDistribucion.getModel()).addRow(new Object[]{new Integer(miv_pro.getValor()), miv_pro.toString(), new Integer(miv_bod.getValor()), miv_bod.toString(), fecha_vencimiento, new Integer(miv_mar.getValor()), miv_mar.toString(), new Integer(miv_prov.getValor()), miv_prov.toString(), 0, 0});
    }//GEN-LAST:event_jbtnDistribuitActionPerformed
    private void jbtnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnQuitarActionPerformed
        ((DefaultTableModel) jtblDistribucion.getModel()).removeRow(jtblDistribucion.getSelectedRow());
    }//GEN-LAST:event_jbtnQuitarActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        selector_fecha.hidePopup();
        selector_fecha = null;
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing
    private void jtfProductoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfProductoKeyTyped
        CargarProducto(evt.getKeyChar());
    }//GEN-LAST:event_jtfProductoKeyTyped

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblDistribucion.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblDistribucion,archivo_excel,"Ingreso y Distribución")){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JButton jbtnDistribuit;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnQuitar;
    private javax.swing.JComboBox jcbBodega;
    private javax.swing.JComboBox jcbMarca;
    private javax.swing.JComboBox jcbProveedor;
    private javax.swing.JList jlstProductos;
    private javax.swing.JPanel jpFechaVencimiento;
    private javax.swing.JTextArea jtaObservaciones;
    private javax.swing.JTable jtblDistribucion;
    private javax.swing.JTextField jtfProducto;
    // End of variables declaration//GEN-END:variables
}